package org.zhuyx.ch02.shili.aop;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;

import java.util.Arrays;

/**
 * @author 茜茜
 * @date 2024-12-06 17:16
 */
public class TransactionAspect {
    private static final Logger log = LogManager.getLogger(LoggerAspect.class);
    @Pointcut(value = "execution(* service..*.*(..))")
    public void pt(){}
    @Before(value = "pt()")
    public void before(JoinPoint jp) {
        log.info("【TransactionAspect前置增强】模拟打开数据库连接并开启事务...");
        log.info("SqlSession sqlSession=MybatisUtil.createSqlSession(false)");
    }
    @AfterReturning(value = "pt()",returning = "result")
    public void afterReturning(JoinPoint jp, Object result) {
    }
    @AfterThrowing(value = "pt()",throwing = "e")
    public void afterThrowing(JoinPoint jp, Throwable e) {
        log.error("【TransactionAspect异常增强】模拟业务异常回滚事物，异常信息为：" + e.getMessage());
        log.info("SqlSession sqlSession.rollback()");
    }
    @After(value = "pt()")
    public void after(JoinPoint jp) {
        log.info("【TransactionAspect后置增强】模拟提交数据库事务...");
        log.info("SqlSession sqlSession.commit()");
    }
//
//    @Before(value = "execution(* service..*.*(..))")
//    public void before(JoinPoint jp) {
////        log.info("【TransactionAspect前置增强】正在调用{}的{}方法。方法入参:{}", jp.getTarget(), jp.getSignature().getName(), Arrays.toString(jp.getArgs()));
//        log.info("【TransactionAspect前置增强】模拟打开数据库连接并开启事务...");
//        log.info("SqlSession sqlSession=MybatisUtil.createSqlSession(false)");
//
//    }
//
//    @AfterReturning(value = "execution(* service..*.*(..))",returning = "result")
//    public void afterReturning(JoinPoint jp, Object result) {
////        log.info("【TransactionAspect后置增强】{}的{}方法正常返回,返回值：{}", jp.getTarget(), jp.getSignature().getName(), result);
//            log.info("【TransactionAspect后置增强】模拟提交数据库事务...");
//            log.info("session.commit()");
//    }
//
//    @AfterThrowing(value = "execution(* service..*.*(..))",throwing = "e")
//    public void afterThrowing(JoinPoint jp, Throwable e) {
//        log.error("【TransactionAspect异常增强】模拟业务异常回滚事物，异常信息为：" + e.getMessage());
//        log.info("session.rollback()");
//    }
//
//    @After(value = "execution(* service..*.*(..))")
//    public void after(JoinPoint jp) {
//        log.info("【TransactionAspect最终增强】模拟业务完成释放资源...");
//        log.info("MybatisUtil.closeSqlSession(sqlSession)");
//    }
}
